package com.yupi.springbootinit.job.cycle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RefreshCache
 * @Description
 * @Author junjun
 * @Date 2023/5/25 19:39
 * @Version V1.0
 */
@Component
@Slf4j
public class RefreshCache {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    List<Long> mainUserList = Arrays.asList(1661006251963719682L);

    //    @Scheduled(fixedRate = 60 * 60 * 1000)
    @Scheduled(cron = "0 59 23 * * ? ")
    public void refreshCache() {
        mainUserList.forEach(userId -> {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            String redisKey = UserConstant.QUERY_PREFIX + userId;
            Page<User> page = userService.page(new Page<>(1, 20), queryWrapper);
            List<UserVO> userVO = userService.getUserVO(page.getRecords());
            try {
                redisTemplate.opsForValue().set(redisKey, userVO, 60 * 60, TimeUnit.SECONDS);
            } catch (Exception e) {
                log.error("redis set error");
            }


        });
    }
}
